#include "head.h"

/*
Usage:服务器主逻辑
*/
#define MAX_THREAD_NUM 2
//
//长短命令分离函数；返回值为0，1，-1；
//0表示交给主线程的epoll和时间轮统一监听的短命令；
//1表示交给线程池处理的长命令；
//-1表示无效命令；
int cmd_analyse(int client_fd,thread_poll* poll){ 
    MSG msg;
    bzero(&msg,sizeof(msg));
    recv(client_fd,&msg,sizeof(msg),MSG_WAITALL);
    switch(msg.cmd){
    case client_exit:
        {
            server_client_exit(client_fd,&msg);
            break;
        }
    case client_login:{
                          server_login(client_fd,&msg);
                          break;
                      }
    case create_account:{
                            server_create_account(client_fd,&msg);
                            break;
                        }
    case cd:{
                server_cd(client_fd,&msg);
                break;
            }
    case ls:{
                server_ls(client_fd,&msg);
                break;
            }
    case upload:{
                    pthread_mutex_lock(&poll->lock);
                    enQueue(client_fd,&poll->sessions);
                    pthread_cond_signal(&poll->cond);
                    pthread_mutex_unlock(&poll->lock);
                    return 1;
                }
    case download:{
                      pthread_mutex_lock(&poll->lock);
                      enQueue(client_fd,&poll->sessions);
                      pthread_cond_signal(&poll->cond);
                      pthread_mutex_unlock(&poll->lock);
                      return 1;
                  }
    case rm:{
                server_rm(client_fd,&msg);
                break;
            }
    case cdir:{
                  server_cdir(client_fd,&msg);
                  break;
              }
    default:return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,0);

    //读取config文件逻辑；
    char ip[50] = {0};
    char port[10]= {0};
    read_config("./config.ini",port,ip);

    thread_poll poll;
    initThreadPoll(&poll,MAX_THREAD_NUM);

    int socket_fd;
    initTcpLink(&socket_fd,ip,port);

    int epoll_fd = epoll_create(1);
    addtoEpoll(epoll_fd,socket_fd);

    printf("server set, prepared to start session \n");

    struct msg_s msg;
    bzero(&msg,sizeof(msg));
    while(true){
        struct epoll_event ready_set[10];
        int ready_num = epoll_wait(epoll_fd,ready_set,10,-1);
        for(int i=0; i<ready_num; i++){
            if(ready_set[i].data.fd == socket_fd){
                int client_fd = accept(socket_fd,NULL,NULL);
                ERROR_CHECK(client_fd,-1,"accept");
                int ret_cmd_analyse = cmd_analyse(client_fd,&poll);
                if(ret_cmd_analyse == -1){
                    printf("error: invalid command!\n");
                }
                if(ret_cmd_analyse == 0){
                    addtoEpoll(epoll_fd,client_fd);
                }
            }
        }
    }

    return 0;
}

